import {
  Button,
  DatePicker,
  Form,
  InputNumber,
  Modal,
  Radio,
  Select,
  message,
  Spin
} from "antd";
import TextArea from "antd/lib/input/TextArea";
import RadioGroup from "antd/lib/radio/group";
import * as React from "react";
import { connect } from "react-redux";
import {
  formItemLayout,
  formSubmit
} from "../../../../../common/config/repeat";
import { OrderTime } from "../components";
import {
  IForm,
  mapDispatchToProps,
  mapStateToProps,
  TProps
} from "./interface";
import {
  MyAxios,
  ResBodyCode,
  IResBody
} from "../../../../../common/config/http";
import { IOwnerSelect } from "../../interfaces";
import moment from "moment";
const { Item } = Form;
const { Option } = Select;
const { success } = Modal;

const View: React.FC<TProps> = props => {
  const { form, formInfo, hide, submit, getTableDatasource, filter } = props;
  const echo = formInfo.echo_edit;

  const { getFieldDecorator, setFieldsValue } = form;

  const [ownerList, setOwnerList] = React.useState<Array<IOwnerSelect>>([]);

  // 当显示修改表单时,根据echo中的ownerUsername字段查询列表
  React.useEffect(() => {
    if (!echo || formInfo.visible_edit == false) {
      return;
    }
    getOwnerList(echo.ownerUsername);
  }, [formInfo.visible_edit]);

  function handleSubmit(e: React.FormEvent) {
    formSubmit(e, form, (values: IForm) => {
      // console.log("values", values);
      // console.log(values.expiryTime.format("YYYY-MM-DD HH:mm:ss"));
      // console.log(values.expiryTime.format("X")); // 10位的时间戳,可以就是我想要的
      if (!echo) {
        message.error("数据不完整");
        message.error("可能是网络不稳定造成,请关闭弹窗重新修改");
        return;
      }
      const data = {
        id: echo.id,
        type: values.type,
        expiryTime: values.expiryTime.format("X"),
        payMoney: values.payMoney,
        ownerId: values.ownerId,
        note: values.note
      };
      // 发送请求
      submit(formInfo, data, res => {
        console.log("res", res);
        if (res.code === ResBodyCode.OK) {
          message.success(res.msg);
          // 显示成功的提示
          showConfirm();
          // 刷新列表
          getTableDatasource(filter);
        } else {
          message.error(res.msg);
        }
      });
    });
  }

  function showConfirm() {
    success({
      title: "Success",
      content: "订单修改成功",
      onOk() {
        hide(formInfo);
      }
    });
  }

  function getOwnerList(username: string) {
    MyAxios.axios
      .post(
        "user/select/query",
        { username },
        { headers: { ...MyAxios.getToken() } }
      )
      .then(res => {
        setOwnerList(res.data);
      });
  }

  const formBody = (
    <Form {...formItemLayout} onSubmit={handleSubmit}>
      <Item label="类型">
        {getFieldDecorator("type", {
          rules: [{ required: true, message: "必填项" }],
          initialValue: echo && echo.type
        })(
          <RadioGroup>
            <Radio key={0} value={0}>
              秒切版
            </Radio>
            <Radio key={1} value={1}>
              15秒版
            </Radio>
          </RadioGroup>
        )}
      </Item>
      {OrderTime(setFieldsValue)}
      <Item label="过期时间" help="默认延长5分钟">
        {getFieldDecorator("expiryTime", {
          rules: [{ required: true, message: "必填项" }],
          initialValue: echo && moment(echo.expiryTime, "X")
        })(<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />)}
      </Item>
      <Item label="支付金额">
        {getFieldDecorator("payMoney", {
          rules: [{ required: true, message: "必填项" }],
          initialValue: echo && echo.payMoney
        })(<InputNumber min={0} precision={2} />)}
      </Item>
      <Item label="所属用户">
        {getFieldDecorator("ownerId", {
          rules: [{ required: true, message: "必填项" }],
          initialValue: echo && echo.ownerId
        })(
          <Select
            showSearch
            placeholder="搜索用户"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={false}
            onSearch={v => {
              if (v) {
                getOwnerList(v);
              } else {
                setOwnerList([]);
              }
            }}
            notFoundContent={null}
          >
            {ownerList.map(item => (
              <Option key={item.id} value={item.id}>
                {item.username}
              </Option>
            ))}
          </Select>
        )}
      </Item>
      <Item label="备注">
        {getFieldDecorator("note", { initialValue: echo && echo.note })(
          <TextArea
            maxLength={255}
            autosize={{ minRows: 2, maxRows: 3 }}
            placeholder="备注"
          />
        )}
      </Item>
    </Form>
  );

  return (
    <Modal
      title="修改订单"
      destroyOnClose
      onCancel={() => hide(formInfo)}
      okText="提交"
      onOk={e => {
        handleSubmit(e);
      }}
      visible={formInfo.visible_edit}
    >
      <Spin spinning={formInfo.loading_edit}>
      <div style={{ marginTop: "10px" }}>{formBody}</div>
      </Spin>
    </Modal>
  );
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create({ name: "修改订单" })(View));
